<template>
  <div class="container">
    <a-modal
      v-model:visible="visible"
      :width="1400"
      draggable
      :footer="false"
      @close="resetFields"
    >
      <template #title>
        {{ formData?.id ? '编辑广告关联' : '新增广告关联' }}
      </template>
      <a-form ref="formRef" layout="vertical" :model="formData">
        <a-space direction="vertical" :size="16">
          <a-card class="general-card">
            <template #title> 必填信息 </template>
            <a-row :gutter="80">
              <a-col :span="4">
                <a-form-item
                  label="平台"
                  field="platform"
                  validate-trigger="input"
                  required
                >
                  <a-select
                    v-model="formData.platform"
                    placeholder="请选择平台"
                    @change="selectApplicationSearch"
                    allow-clear
                  >
                    <a-option :value="0">微信公众号</a-option>
                    <a-option :value="1">微信小程序</a-option>
                    <a-option :value="2">微信app</a-option>
                    <a-option :value="3">阿里公众号</a-option>
                    <a-option :value="4">阿里小程序</a-option>
                    <a-option :value="5">阿里app</a-option>
                    <a-option :value="6">硬件广告屏</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item field="appid" label="appid" required>
                  <a-select
                      :loading="loading"
                      placeholder="请输入"
                      allow-search
                      allow-clear
                      @search="applicationSearch"
                      :filter-option="false"
                      v-model="formData.appid"
                  >
                    <a-option v-for="item of applicationList" :value="item.appid">{{
                        item.applicationName
                      }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item field="scenes" label="场景" required>
                  <a-select
                      :loading="loading"
                      allow-clear
                      :filter-option="false"
                      v-model="formData.scenes"
                  >
                    <a-option v-for="item of scenesOptions" :value="item.value">{{
                        item.label
                      }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col  :span="6">
                <a-form-item label="载体" field="carrierId">
                  <a-select
                      v-model="formData.type"
                      :options="typeOptions"
                      placeholder="请选择类型"
                      @change="handleShopSearch('')"
                      allow-clear
                  />
                  <a-select v-model="formData.carrierId" :loading="loading" placeholder="输入店铺名" allow-search :allow-clear=true
                            :filter-option="false" @search="handleShopSearch">
                    <a-option v-for="item of shopList" :key="item?.id" :value="item?.id">{{ item.name }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="投放时间" field="launchTime">
                  <a-range-picker
                    v-model="formData.launchTime"
                    showTime
                    :time-picker-props="{
                    defaultValue:['00:00:00','00:00:00']
                    }"
                    @change="onStartTimeChange"
                    style=" width: 380px; "
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="排序"
                  field="sortIndex"
                  validate-trigger="input"
                >
                  <a-input
                    v-model="formData.sortIndex"
                    placeholder="请输入排序"
                    allow-clear
                  ></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-space>
        <div class="actions">
          <a-space>
            <a-button @click="resetFields"> 重置 </a-button>
            <a-button type="primary" :loading="loading" @click="onSubmitClick">
              保存
            </a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import {
    addLink,
    updateLink,
    getAdListByQuery,
    cfDeveloperGet,
  } from '@/api/user';
  import {cfCarParkSearch, cfChargingStationSearch} from "@/api/internetOfThings";
  import {cfVillageSearch} from "@/api/wisdomCommunity";
  import { Message } from '@arco-design/web-vue';
  import { getToken } from '@/utils/auth';
  import dayjs from 'dayjs';
  import { parseTime } from '@/utils';
  import { cloneDeep } from 'lodash';

  const visible = ref(false);
  const loading = ref(false);
  const formRef = ref();
  const applicationList = ref([]);
  const shopList = ref([]);
  const emit = defineEmits(['fetchData', 'fetch-data']);
  const formData = ref({
    id: null,
    adId: null,
    scenes: '',
    platform: '',
    carrierId: '',
    sortIndex: '',
    startTime: '',
    endTime: '',
    showCounts: '',
    clickCounts: '',
    issuanceTime: '',
    appid: '',
    applicationName: '',
    type: '',
    launchTime: [],
  });

  const roleList = ref([]);
  const file = ref();
  const header: any = ref({
    Authorization: getToken(),
  });
  onMounted(() => {
    applicationSearch(null);
    fetchData()
  });
  const fetchData = async () => {
    // @ts-ignore
    const { data, code } = await getAdListByQuery({
      params: {
        page: 1,
        size: 10,
      },
    });
    if (code === 10002) {
      roleList.value = data;
    }
  };
  /**
   * 搜索店铺（判断类型）
   * @param value
   */
  const handleShopSearch = async (value: any) => {
    if(formData.value.type==1){
      //停车
      const { data, code } = await cfCarParkSearch({
        params: {
          name: value,
          page: 1,
          size: 200,
        },
      });
      if (code === 10002) {
        shopList.value = data;
      } else {
        shopList.value = [];
      }
    } else if(formData.value.type==3){
      //充电
      const { data, code } = await cfChargingStationSearch({
        params: {
          stationName: value,
          page: 1,
          size: 200,
        },
      });
      if (code === 10002) {
        shopList.value = data;
      } else {
        shopList.value = [];
      }
    } else if(formData.value.type==6){
      //智慧社区
      const { data, code } = await cfVillageSearch({
        params: {
          name: value,
          page: 1,
          size: 200,
        },
      });
      if (code === 10002) {
        shopList.value = data;
      } else {
        shopList.value = [];
      }
    }else{
      //其它暂不支持
      shopList.value = [];
    }

  };
  const onStartTimeChange = (dateString: any, date: Date[]) => {
    if(date!=undefined){
      formData.value.startTime = date[0];
      formData.value.endTime = date[1];
    }else{
      formData.value.startTime = '';
      formData.value.endTime = '';
    }
    
  };
  const selectApplicationSearch = async (_platform: any) => {
    formData.value.platform = _platform
    applicationSearch(null)
  };
  const applicationSearch = async (_applicationName: any) => {
    let _platform = '';
    switch (formData.value.platform){
      case 0:
        _platform = 'wx_web';
        break;
      case 1:
        _platform = 'wx_mp';
        break;
      case 2:
        _platform = 'wx_app';
        break;
      case 3:
        _platform = 'ali_web';
        break;
      case 4:
        _platform = 'ali_mp';
        break;
      case 5:
        _platform = 'ali_app';
        break;
      case 6:
        _platform = '';
        break;
    }
    const { data, code } = await cfDeveloperGet({
      params: {
        page: 1,
        size: 200,
        applicationName: _applicationName,
        platform: _platform,
      },
    });
    if (code == 10002) {
      applicationList.value = data;
    } else {
      applicationList.value = [];
    }
  };
  const scenesOptions = [
    {
      label: '车牌绑定页面',
      value: 0,
    },
    {
      label: '停车账单结算页面',
      value: 1,
    },
    {
      label: '支付成功页面',
      value: 2,
    },
    {
      label: '停车场详情',
      value: 3,
    },
    {
      label: '充电站详情',
      value: 4,
    },
    {
      label: '停车套餐续费页面',
      value: 5,
    },
    {
      label: '优惠券活动充值',
      value: 6,
    },
    {
      label: '充电中页面',
      value: 7,
    },
    {
      label: '充电账单详情页面',
      value: 8,
    },
    {
      label: '硬件显示屏',
      value: 9,
    },
    {
      label: '移动应用首页',
      value: 10,
    },
    {
      label: '领取优惠券页面',
      value: 11,
    },
    {
      label: '订单详情页面',
      value: 12,
    },
  ];
  const typeOptions = [
    {
      label: '停车',
      value: 1,
    },
    {
      label: '商城',
      value: 2,
    },
    {
      label: '充电',
      value: 3,
    },
    {
      label: '洗车',
      value: 4,
    },
    {
      label: '加油',
      value: 5,
    },
    {
      label: '社区',
      value: 6,
    }
  ];
  const handleClick = (e: any = null) => {

    if (e?.id) {
      e.launchTime = [];
      e.launchTime[0] = parseTime(e.startTime);
      e.launchTime[1] = parseTime(e.endTime);
      const newInfo = JSON.parse(JSON.stringify(e));
      newInfo.startTime = parseTime(e.startTime)
      newInfo.endTime = parseTime(e.endTime)
      
      // newInfo.endTime = e.roleEndTime === null ? 0 : parseTime(e.roleEndTime)
      formData.value = newInfo;
    }
    formData.value.adId = e.adId;
    visible.value = true;
  };
  const resetFields = () => {
    formRef.value.avatar = '';
    formRef.value.avatarUrl = '';
    formRef.value.resetFields();
  };
  const onSubmitClick = () => {
    // eslint-disable-next-line consistent-return
    formRef.value.validate(async (valid: any) => {
      if (valid) return false;
      const newForm = cloneDeep(formData.value);
      newForm.startTime = dayjs(formData.value.startTime).valueOf();
      newForm.endTime = dayjs(formData.value.endTime).valueOf();
      // @ts-ignore
      // @ts-ignore
      if (formData.value.id) {
        const { code } = await updateLink(newForm);
        if (code === 10002) {
          formData.value.id = '';
          formRef.value.resetFields();
          visible.value = false;
          Message.success('更新成功!');
          emit('fetchData');
        }
      } else {
        const { code } = await addLink(newForm);
        if (code === 10002) {
          formData.value.id = '';
          formRef.value.resetFields();
          visible.value = false;
          Message.success('添加成功!');
          emit('fetchData');
        }
      }
    });
  };

  defineExpose({ handleClick });
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 40px 20px;
    overflow: hidden;
  }

  .actions {
    height: 60px;
    padding: 14px 20px 14px 0;
    background: var(--color-bg-2);
    text-align: right;
  }
</style>
